<template>
  <el-container>
    <el-header><h3 class="header-title">清明档案展示管理端</h3></el-header>
    <el-main>
      <el-tabs v-model="dynasty" @tab-click="switchTab">
        <el-tab-pane label="清朝档案" name="Qing"></el-tab-pane>
        <el-tab-pane label="民国档案" name="POC"></el-tab-pane>
      </el-tabs>

      <el-button-group>
        <el-button icon="el-icon-plus" size="small" @click="add"></el-button>
        <el-button icon="el-icon-edit" size="small" @click="edit"
                   :disabled="multipleSelection.length !== 1"></el-button>
        <el-button icon="el-icon-delete" size="small" class="del-btn"
                   @click="remove"
                   :disabled="multipleSelection.length === 0"></el-button>
      </el-button-group>

      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">>
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          prop="fullname"
          label="全宗名称"
          width="120">
        </el-table-column>
        <el-table-column
          prop="year"
          label="年度"
          width="60">
        </el-table-column>
        <el-table-column
          prop="keepDate"
          label="保管期限">
        </el-table-column>
        <el-table-column
          prop="boxNo"
          label="盒号"
          width="100">
        </el-table-column>
        <el-table-column
          prop="unitNo"
          label="件号">
        </el-table-column>
        <el-table-column
          prop="title"
          label="题名">
        </el-table-column>
        <el-table-column
          prop="liablePerson"
          label="责任人"
          width="100">
        </el-table-column>
        <!--<el-table-column
          prop="time"
          label="时间"
          width="100">
        </el-table-column>
        <el-table-column
          prop="pageCount"
          label="页数"
          width="100">
        </el-table-column>
        <el-table-column
          prop="secretLevel"
          label="密级"
          width="100">
        </el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          width="100">
        </el-table-column>-->
        <el-table-column
          prop="type"
          label="档案类别"
          width="100">
        </el-table-column>
      </el-table>

      <archive-add :visible.sync="visible" :formData.sync="form"
                   @submitSuccess="getList"></archive-add>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>

      <h3>数据模拟</h3>
      <el-button-group>
        <el-button size="small" @click="initDB">初始化数据库</el-button>
        <el-button size="small" @click="clearDB">清空数据库</el-button>
      </el-button-group>
    </el-main>
  </el-container>
</template>

<script>
  import ArchiveAdd from './Add.vue'
  import ArchiveModel from '../../model'

  export default {
    name: 'archive-list',

    components: {
      ArchiveAdd
    },

    data() {
      return {
        dynasty: 'Qing',
        tableData: [],
        page: 1,
        pageSize: 10,
        total: 0,
        multipleSelection: [],
        visible: false,
        form: {
          ...ArchiveModel
        }
      }
    },

    methods: {
      switchTab() {
        this.getList()
      },
      getList() {
        this.$db.find({type: this.dynasty})
          .sort({addDate: -1})
          .exec((err, doc) => {
            if (err) {
              this.$message.error('error occur')
              return
            }

            console.log(doc)
            this.total = doc.length
            this.tableData = doc.splice((this.page - 1) * this.pageSize, this.pageSize)
          })
      },
      handleSizeChange (val) {
        this.pageSize = val
        this.getList()
      },
      handleCurrentChange (val) {
        this.page = val
        this.getList()
      },
      handleSelectionChange (val) {
        this.multipleSelection = val
        console.log(val)
      },
      add() {
        console.log(ArchiveModel)
        this.form = ArchiveModel
        this.visible = true
      },
      edit() {
        const len = this.multipleSelection.length
        if (len !== 1) return

        console.log(JSON.stringify(this.multipleSelection[0], null, ' '))
        this.form = this.multipleSelection[0]
        this.visible = true
      },
      remove() {
        const len = this.multipleSelection.length
        if (len === 0) return

        this.$confirm(`是否删除当前选中的${len}条数据?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.multipleSelection.forEach((item) => {
            this.$db.remove({_id: item._id}, {}, (err) => {
              if (err) this.$message.error('删除失败')
            })
          })

          this.$message.success({
            message: '删除成功',
            duration: 1000,
            onClose: () => this.getList()
          })
        }).catch(() => {})
      },
      initDB() {
        this.clearDB()

        const row = {
          fullname: '张三',
          year: 1790,
          keepDate: new Date().getTime(),
          boxNo: '123421',
          unitNo: '234132',
          title: '题名',
          liablePerson: '责任人',
          time: new Date().getTime(),
          pageCount: 123,
          secretLevel: 3,
          remark: '备注',
          addDate: new Date('2017-10-01').getTime()
        }

        let rows = []
        for (let i = 0; i < 100; i++) {
          rows.push({
            ...row,
            fullname: row.fullname + i,
            year: row.year + i,
            title: row.title + i,
            time: new Date().getTime(),
            pageCount: row.pageCount + i,
            secretLevel: row.secretLevel + i,
            remark: row.remark + i,
            type: Math.random() > 0.5 ? 'Qing' : 'POC',
            addDate: row.addDate + 1000 * i
          })
        }

        this.$db.insert(rows, (err, newDoc) => {
          if (err) {
            this.$message.error('init database fail')
            return
          }

          console.log(newDoc)
          this.$message.success({
            duration: 1000,
            message: 'init database success',
            onClose: () => this.getList()
          })
        })
      },
      clearDB() {
        this.$db.remove({}, {multi: true}, (err, numRemoved) => {
          if (err) {
            this.$message.error('clear database fail')
            return
          }

          this.$message.success({
            duration: 1000,
            message: `clear database success, ${numRemoved} removed`,
            onClose: () => this.getList()
          })
        })
      }
    },

    created() {
      this.getList()
    }
  }
</script>

<style>
  .header-title {
    border-bottom: 1px solid lightgray;
    padding-bottom: 10px;
    color: #333;
  }

  .del-btn:hover, .del-btn:focus {
    color: #fa5555;
    background-color: #fee;
    border-color: #fdbbbb;
  }
</style>
